const homework = require('../models/homework')
const point = require('../models/point')
const question = require('../models/question')
const workRecord = require('../models/workRecords')
const users= require('../models/userDetail')

var express = require('express')
var router = express.Router()

var formidable = require('formidable')

router.post('/', (req, res, next) => {
    var form = new formidable.IncomingForm()
    form.parse(req, function(err, fields, files) {
        if(err) {
            res.json({'state': false, 'msg': err})
        } else {
            var find_point = (point_id) => {
                return new Promise(function (resolve, reject) {
                    point.findOne({
                        _id: point_id
                    }, (err, doc) => {
                        if(err) {
                            res.json({'state': false, 'msg': err})
                        }else {
                            resolve(doc);
                        }
                    })
                })
            }

            var find_question = (point_id, question_id) => {
                return new Promise(function (resolve, reject) {
                    point.findOne({
                        _id: point_id
                    }, (err, p) => {
                        if(err) {
                            res.json({'state': false, 'msg': err})
                        }else{
                            question.findOne({
                                _id: question_id
                            }, (err, doc) => {
                                if(err) {
                                    res.json({'state': false, 'msg': err})
                                }else {
                                    resolve({
                                        point: p,
                                        question: doc
                                    })
                                }
                            })
                        }
                    })
                })
            }

            var stu_num = (flags) =>{
                return new Promise(function (resolve, reject) {
                    users.find({
                        flags: {
                            $all:flags
                        }
                    }, (err, doc) => {
                        if(err) {
                            res.json({'state': false, 'msg': err})
                        }else{
                            resolve(doc.length)
                        }
                    })
                })
            }

            var update_num = (UUID, seq, stu_num) => {
                return new Promise(function (resolve, reject) {
                    homework.findOne({
                        UUID: UUID,
                        seq: seq
                    }, (err, h) => {
                        if(err) {
                            res.json({'state': false, 'msg': err})
                        }else{
                            h.stu_num = stu_num;
                            h.save(err => {
                                if(err) {
                                    res.json({'state':false, 'msg': err})
                                }else {
                                    resolve("save!")
                                }
                            })
                        }
                    });
                });
            }
            if(fields.UUID){
                homework.find({
                    UUID: fields.UUID
                }, {UUID:0}, {sort: 'seq'}, async (err, homeworks) => {
                    if(err) {
                        res.json({'state': false, 'msg': err})
                    } else {
                        let works = []
                        for(var i=0;i<homeworks.length;i++){
                            let new_num = await stu_num(homeworks[i].flags).then()
                            if(new_num !== homeworks[i].stu_num){
                                let info = await update_num(fields.UUID, homeworks[i].seq, new_num).then()
                                // console.log(info);
                            }
                            let tmp_work = {};
                            tmp_work.flags = homeworks[i].flags;
                            tmp_work.seq = homeworks[i].seq;
                            tmp_work.name = homeworks[i].name;
                            tmp_work.submit_num = homeworks[i].submit_num;
                            tmp_work.need = homeworks[i].need;
                            tmp_work.time = homeworks[i].time;
                            tmp_work.stu_num = new_num;
                            tmp_work.type = homeworks[i].type;
                            tmp_work.is_late = homeworks[i].is_late;
                            question_list = []
                            if(homeworks[i].type === 'timu') {
                                let q = homeworks[i].question;
                                for(var j=0;j<q.length;j++) {
                                    let item = q[j];
                                    if(item.questionId) {
                                        let tmpquestion = await find_question(item.pointId,item.questionId).then();
                                        if(tmpquestion.point && tmpquestion.question){
                                            let tmpquestion1 = {
                                                _id: tmpquestion.question.point_id,
                                                items: tmpquestion.question.items,
                                                answer: tmpquestion.question.answer,
                                                question_id: item.questionId,
                                                question: tmpquestion.question.question,
                                                type: tmpquestion.question.type,
                                                illustrationContent: tmpquestion.question.illustrationContent,
                                                bloom: tmpquestion.question.bloom
                                            }
                                            question_list.push(tmpquestion1);
                                        }
                                    }else {
                                        let tmppoint = await find_point(item.pointId).then()
                                        if(tmppoint){
                                            let tmppoint1 = {
                                                _id: item.pointId,
                                                items: tmppoint.practice.items,
                                                answer: tmppoint.practice.answer,
                                                question_id: "",
                                                question: tmppoint.practice.question_editor_Content,
                                                type: tmppoint.practice.type,
                                                illustrationContent: tmppoint.practice.illustrationContent,
                                                bloom: tmppoint.bloom
                                            }
                                            question_list.push(tmppoint1);
                                        }
                                    }
                                }
                                tmp_work.question_list = question_list;
                            }
                            works.push(tmp_work);
                        }
                        res.json({
                            'state': true,
                            'homeworks': works
                        })
                    }
                })
            }else if(fields.flags){
                // var flags = fields.flags;
                homework.find({},{submit_num: 0, stu_num:0, question:0}, {sort: 'seq'}, async (err, homeworks) => {
                    if(err) {
                        res.json({'state': false, 'msg': err});
                    }else {
                        workRecord.find({
                            UUID: fields.stu_UUID
                        }, {seq:1}, (err, submit) => {
                            if(err) {
                                res.json({'state': false, 'msg': err})
                            }else {
                                let submit_list = [];
                                submit.forEach(s => {
                                    submit_list.push(s.seq);
                                })
                                let works = []
                                homeworks.forEach(h => {
                                    if(h.flags.every(val => fields.flags.includes(val))){
                                        let is_submit = false;
                                        if(submit_list.indexOf(h.seq) !== -1){
                                            is_submit = true;
                                        }
                                        works.push({
                                            _id: h._id,
                                            UUID: h.UUID,
                                            seq: h.seq,
                                            name: h.name,
                                            need: h.need,
                                            type: h.type,
                                            time: h.time,
                                            is_late: h.is_late,
                                            is_submit: is_submit
                                        })
                                    }
                                })
                                res.json({
                                    'state': true,
                                    'homeworks': works,
                                })
                            }
                        })
                        // let works = []
                        // for(var i=0;i<homeworks.length;i++){
                        //     let tmp_work = {};
                        //     tmp_work.seq = homeworks[i].seq;
                        //     tmp_work.name = homeworks[i].name;
                        //     tmp_work.need = homeworks[i].need;
                        //     tmp_work.time = homeworks[i].time;
                        //     tmp_work.type = homeworks[i].type;
                        //     tmp_work.is_late = homeworks[i].is_late;
                        //     question_list = []
                        //     if(homeworks[i].type === 'timu') {
                        //         let q = homeworks[i].question;
                        //         for(var j=0;j<q.length;j++) {
                        //             let item = q[j];
                        //             if(item.questionId) {
                        //                 let tmpquestion = await find_question(item.pointId,item.questionId).then();
                        //                 if(tmpquestion.point && tmpquestion.question){
                        //                     let tmpquestion1 = {
                        //                         _id: tmpquestion.question.point_id,
                        //                         title: tmpquestion.point.title,
                        //                         content: tmpquestion.point.content,
                        //                         items: tmpquestion.question.items,
                        //                         question_id: item.questionId,
                        //                         question: tmpquestion.question.question,
                        //                         type: tmpquestion.question.type,
                        //                         bloom: tmpquestion.question.bloom
                        //                     }
                        //                     question_list.push(tmpquestion1);
                        //                 }
                        //             }else {
                        //                 let tmppoint = await find_point(item.pointId).then()
                        //                 if(tmppoint){
                        //                     let tmppoint1 = {
                        //                         _id: item.pointId,
                        //                         title: tmppoint.title,
                        //                         content: tmppoint.content,
                        //                         items: tmppoint.practice.items,
                        //                         question_id: "",
                        //                         question: tmppoint.practice.question_editor_Content,
                        //                         type: tmppoint.practice.type,
                        //                         bloom: tmppoint.bloom
                        //                     }
                        //                     question_list.push(tmppoint1);
                        //                 }
                        //             }
                        //         }
                        //         tmp_work.question_list = question_list;
                        //     }
                        //     works.push(tmp_work);
                        // }
                        // res.json({
                        //     'state': true,
                        //     'homeworks': works
                        // })
                    }
                })
            }else {
                res.json({
                    'state': false,
                    'msg': '请求参数错误！'
                })
            }
        }
    });
});

module.exports = router